import os
import time
from pyramid.authentication import SessionAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from pyramid_beaker import (session_factory_from_settings, 
    set_cache_regions_from_settings)
from stockforecaster.config import globalize_settings
from stockforecaster.models import initialize_sqla


def main(global_config, **settings):
    '''
    Configure and return a WSGI application.
    '''
    globalize_settings(settings)
    initialize_sqla(settings)
    set_cache_regions_from_settings(settings)
    config = Configurator(
        settings=settings,
        authentication_policy=SessionAuthenticationPolicy(),
        authorization_policy=ACLAuthorizationPolicy(),
        session_factory=session_factory_from_settings(settings))
    config.include('pyramid_celery')
    config.include('pyramid_jinja2')
    config.include('pyramid_rewrite')
    config.include('pyramid_tm')
    config.include('stockforecaster.config.routes')
    config.add_renderer('.html', 'pyramid_jinja2.renderer_factory')
    config.add_static_view(settings['static_url'], 'stockforecaster:static')
    config.scan()
    os.environ['TZ'] = settings['timezone']
    time.tzset()
    return config.make_wsgi_app()